package com.kuanrf.upload.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kuanrf.common.base.BaseActionSupport;
import com.kuanrf.common.tools.FileTools;
import com.kuanrf.common.tools.StringTools;
import com.kuanrf.common.util.PropertyUtils;
import com.kuanrf.upload.util.IM4Java;
import com.kuanrf.upload.util.KinderTools;

public class UploadAction extends BaseActionSupport {

	private static final long serialVersionUID = -4535422695433658304L;

	/**
	 * 日志记录<br>
	 */
	private final Log logger = LogFactory.getLog(getClass());

	/**
	 * 文件上传路径，相对于默认路径
	 */
	private String path;

	/**
	 * 文件
	 */
	private File file;

	/**
	 * 参数传过来的真实文件名
	 */
	private String fileName;

	/**
	 * Struts临时文件名称
	 */
	private String fileFileName;

	/**
	 * 为了避免报错，加上这个参数
	 */
	private String fileContentType;

	/**
	 * 图片服务器URL地址
	 */
	private String fileServer = "";

	/**
	 * 默认目录
	 */
	private String defaultRoot;

	/**
	 * 文件上传本地绝对根目录
	 */
	private String rootPath;

	/**
	 * 图片是否压缩 true :需要压缩 false：不需要压缩
	 */
	private boolean imgCompress = false;

	/**
	 * 图片是否等比例压缩，true：等比例压缩，false：不等比例压缩
	 */
	private boolean imgRatio = false;

	/**
	 * 图片宽度
	 */
	private int imgWidth = 200;

	/**
	 * 图片高度
	 */
	private int imgHeight = 266;

	/**
	 * 是否以原文件名保存，true:原文件名保存；false：重命名保存
	 */
	private boolean saveByRealName = false;

	/**
	 * <默认构造函数>
	 */
	public UploadAction() {
		super();
		fileServer = PropertyUtils.getValue("file.server.url");
		rootPath = PropertyUtils.getValue("file.upload.rootPath");
		defaultRoot = PropertyUtils.getValue("file.upload.defaultPath");
	}

	/**
	 * 保存文件到服务器上,直接响应文件的完整URL地址</br> 文件保存路径为: rootPath/defaultRoot/path/文件名</br>
	 * 返回文件URL为:imageServer/defaultRoot/path/文件名
	 * 
	 * @return
	 * @throws Exception
	 */
	@Override
	public String execute() throws Exception {
		// 检查请求消息头
		boolean ckr = super.checkRequestHeader();
		if (!ckr) {
			return null;
		}
		// 判断文件是否为空
		if (file == null) {
			return null;
		}
		if (StringTools.isNullOrNone(fileName)) {
			return null;
		}
		String httpFileUrl = null;// 返回的文件路径
		String fullFilePath = null;// 文件本地保存路径
		String fileSubstr = null;// 文件后缀名
		// 文件后缀
		fileSubstr = fileName.substring(fileName.lastIndexOf('.'));
		if (!StringTools.isNullOrNone(fileSubstr)) {
			fileSubstr = fileSubstr.toLowerCase();
			if (fileSubstr.contains("jsp") || fileSubstr.contains("php")
					|| fileSubstr.contains("asp") || fileSubstr.contains("exe")) {
				logger.error("上传文件错误，不支持的文件类型:" + fileSubstr);
				return null;
			}
		} else {
			logger.error("文件没有后缀名，上传失败!");
			return null;
		}
		String saveName = KinderTools.getUUID() + fileSubstr;
		if (saveByRealName) {
			saveName = fileName;
		}

		httpFileUrl = fileServer + defaultRoot;
		fullFilePath = rootPath + defaultRoot;

		if (StringTools.isNullOrNone(path)) {
			httpFileUrl += "/" + saveName;
			fullFilePath += "/" + saveName;
		} else {
			if (!path.startsWith("/")) {
				path = "/" + path;
			}
			if (path.endsWith("/")) {
				httpFileUrl += path + saveName;
				fullFilePath += path + saveName;
			} else {
				httpFileUrl += path + "/" + saveName;
				fullFilePath += path + "/" + saveName;
			}

		}
		// 文件路径是否存在
		File localFile1 = new File(fullFilePath);
		File localFile2 = localFile1.getParentFile();
		// 创建目录
		if (!(localFile2.isDirectory()))
			localFile2.mkdirs();
		try {
			FileTools.copyFile(file, localFile1);
		} catch (Exception e) {
			return null;
		}

		// 文件压缩
		if (imgCompress) {
			try {
				if (imgRatio) {
					imgWidth = imgWidth > 0 ? imgWidth : 1;
					imgHeight = imgHeight > 0 ? imgHeight : 1;
					File file = new File(fullFilePath);
					FileInputStream fis = new FileInputStream(file);
					BufferedImage bufferedImg = ImageIO.read(fis);
					int imgWidthM = bufferedImg.getWidth();
					int imgHeightM = bufferedImg.getHeight();
					fis.close();
					float whm = (float) imgWidthM / (float) imgHeightM;
					float wh = (float) imgWidth / (float) imgHeight;
					if (whm > wh) {
						if (imgWidth > imgWidthM) {
							imgWidth = imgWidthM;
						}
						imgHeight = (int) (imgWidth / whm);
					} else {
						if (imgHeight > imgHeightM) {
							imgHeight = imgHeightM;
						}
						imgWidth = (int) (imgHeight * whm);
					}
				}
				IM4Java.cropImageCenter(fullFilePath, fullFilePath, imgWidth,
						imgHeight);
			} catch (Exception ex) {
				logger.error("图片压缩出错，" + ex);
			}
		}

		return ajax(httpFileUrl, "text/html");
	}

	/**
	 * @return 返回 path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @param 对path进行赋值
	 */
	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * @return 返回 file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param 对file进行赋值
	 */
	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return 返回 fileFileName
	 */
	public String getFileFileName() {
		return fileFileName;
	}

	/**
	 * @param 对fileFileName进行赋值
	 */
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	/**
	 * @param 对fileContentType进行赋值
	 */
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	/**
	 * @return 返回 fileContentType
	 */
	public String getFileContentType() {
		return fileContentType;
	}

	/**
	 * @return 返回 fileName
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * @param 对fileName进行赋值
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public boolean isImgCompress() {
		return imgCompress;
	}

	public void setImgCompress(boolean imgCompress) {
		this.imgCompress = imgCompress;
	}

	public int getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(int imgWidth) {
		this.imgWidth = imgWidth;
	}

	public int getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(int imgHeight) {
		this.imgHeight = imgHeight;
	}

	public boolean isSaveByRealName() {
		return saveByRealName;
	}

	public void setSaveByRealName(boolean saveByRealName) {
		this.saveByRealName = saveByRealName;
	}

	public boolean isImgRatio() {
		return imgRatio;
	}

	public void setImgRatio(boolean imgRatio) {
		this.imgRatio = imgRatio;
	}

}
